package dk.au.cs.peterbn.xml;

import com.thaiopensource.validation.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

/**
 * Static helper class to initialize relax-ng schemas
 */
public class XmlProvider {
    private static final Logger logger = LoggerFactory.getLogger(XmlProvider.class);
    static ClassLoader classLoader = XmlProvider.class.getClassLoader();
    static SchemaFactory schemaFactory = SchemaFactory.newInstance(Constants.RELAXNG_COMPACT_URI, "com.thaiopensource.relaxng.jaxp.CompactSyntaxSchemaFactory", classLoader);
    static {

        schemaFactory.setResourceResolver(new SchemaResolver());
    }

    public static Schema getPatternSchema() {
        return initSchema("designpattern");
    }

    public static Schema getExternalsSchema() {
        return initSchema("external");
    }

    private static Schema initSchema(String schemaname) {
        Source schemaSource = new StreamSource(classLoader.getResourceAsStream("schemas/" + schemaname + ".rnc"));
        try {
            return schemaFactory.newSchema(schemaSource);
        } catch (SAXException e) {
            logger.error("Error initializing RelaxNG schema", e);
            throw new RuntimeException(e); //I REALLY don't want to get here
        }
    }
}
